import { defineStore } from 'pinia'
//引入接口
import { requestLogin,requestUserInfo,requestLogout  } from '@/api/user'

import type { loginParams,loginResponseData,userInfoResponseData   } from '@/api/user/type'
import type { userState } from './types/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRoute } from '@/router/routes'

let useUserStore = defineStore('User',{
    state:():userState=>{
        return {
            token: GET_TOKEN(),
            menuRoutes: constantRoute,//生成菜单动态数组
            username:'',
            avatar:''
        }
    },
    actions:{
        async userLogin(data:loginParams){
            let result:loginResponseData  = await requestLogin(data)
            if(result.code == 200){
                this.token = (result.data as string)
                SET_TOKEN((result.data as string))
                return 'ok';
            }else{
                return Promise.reject(new Error(result.data))
            }
        },
        //获取用户信息
        async userInfo(){
            let result:userInfoResponseData  = await requestUserInfo()
            if(result.code == 200){
                let { name,avatar } = result.data
                this.username = name as string
                this.avatar = avatar as string
                return 'ok';
            }else{
                return Promise.reject(new Error(result.message))
            }
        },
        //退出登录
        async userLogout(){
            let result:any = await requestLogout()
            if(result.code == 200){
                this.token = '';
                this.username = '';
                this.avatar = '';
                REMOVE_TOKEN()
            }else{
                return Promise.reject(new Error(result.message))
            }
        }
    },
    getters:{

    }
})

export default useUserStore